package com.ljc.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ljc.model.entity.Wallpaper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static com.ljc.utils.SignUtils.genSign;

/**
 * 调用第三方接口的客户端
 */
public class ApiPlatformClient {

    private static final String GATEWAY_HOST = "http://keep-moving.cn/api/";
//    private static final String GATEWAY_HOST = "http://localhost:8002";

    private String accessKey;

    private String secretKey;

    public ApiPlatformClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        // 一定不能直接发送
//        hashMap.put("secretKey", secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        try {
            hashMap.put("body", URLEncoder.encode(body, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", genSign(body, secretKey));
        return hashMap;
    }

    /**
     * 获取壁纸
     */
    public String getWallpaper(Wallpaper wallpaper) {
        String json = JSONUtil.toJsonStr(wallpaper);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/api/interface/wallpaper")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        return httpResponse.body();
    }

    /**
     * 获取心灵鸡汤
     */
    public String getMotivationalSentence() {
        return HttpRequest.get(GATEWAY_HOST + "/api/interface/sentence")
                .addHeaders(getHeaderMap(""))
                .execute().body();
    }

    /**
     * 获取随机头像
     */
    public String getAvatar() {
        return HttpRequest.get(GATEWAY_HOST + "/api/interface/avatar")
                .addHeaders(getHeaderMap(""))
                .execute().body();
    }

    /**
     * 获取笑话
     */
    public String getJoke() {
        return HttpRequest.get(GATEWAY_HOST + "/api/interface/joke")
                .addHeaders(getHeaderMap(""))
                .execute().body();
    }

    /**
     * 获取外卖种类
     */
    public String getTakeOut() {
        return HttpRequest.get(GATEWAY_HOST + "/api/interface/takeout")
                .addHeaders(getHeaderMap(""))
                .execute().body();
    }
}
